import {Client} from 'ssh2'
import {MessageBox} from 'element-ui';
class SSHClient {
    /** */
    constructor (server) {
        let $this = this;
        this.client = new Client();
        this.client.on('close', () => { $this.handleClientOnClosed(); });
        this.client.on('keyboard-interactive', () => {
            console.log('xxxx');
         });

        this.server = server;
        this.isConnected = false;
    }

    // 断开连接
    handleClientOnClosed() {
        MessageBox.alert('服务器断开连接', '', {
            confirmButtonText: '确定',
            callback: () => {
                window.app.$store.dispatch('serverCurClosed');
            }
        });
    }

    // 获取是否已经连接到服务器
    getIsConnected() {
        return this.isConnected;
    }

    /** 链接到服务器 */
    async connect()  {
        if ( this.isConnected ) {
            return;
        }
        
        await this.connectByPassword(
            this.server.host,
            this.server.port,
            this.server.username,
            this.server.password
        );

        
    }

    /** 通过用户名密码连接到服务器 */
    connectByPassword(host, port, username, password ) {
        let $this = this;
        return new Promise(( resolve, reject ) => {
            $this.client.on('ready', () => {
                $this.isConnected = true;
                resolve();
            });
            $this.client.on('error', ( err ) => {
                reject(err);
            });
            $this.client.connect({
                host: host,
                port:port,
                username:username,
                password:password,
            });
        });
    }

    /** 断开连接 */
    disconnect() {
        this.client.end();
    }

    /** 执行命令 */
    exec( cmd ) {
        console.log(`[SSHClient::exec] ${cmd}`);
        let $this = this;
        return new Promise(( resolve, reject ) => {
            $this.client.exec(cmd, {pty:true}, (error, stream) => {
                if (undefined != error) {
                    reject(error);
                }

                let stdout = '';
                let stderr = '';
                stream.on('close', (code, signal) => {
                    console.log(`[SSHClient::exec(${cmd})]\n${stdout}`);
                    resolve(stdout);
                });
                stream.on('data', (data) => { stdout += data; });
                stream.stderr.on('data', (data) => { stderr += data; });
            });
        });
    }

    /** 执行 */
    exec4Stream( cmd ) {
        console.log(`[SSHClient::exec4Stream] ${cmd}`);
        let $this = this;
        return new Promise(( resolve, reject ) => {
            $this.client.exec(cmd, {pty:true}, (error, stream) => {
                if (undefined != error) {
                    reject(error);
                } else {
                    resolve(stream);
                }
            });
        });
    }

    /** 写入文件到服务器 */
    filePutContent( path, content ) {
        let $this = this;
        return new Promise(( resolve, reject ) => {
            $this.client.sftp((err, sftp) => {
                if (err) {
                    reject(err);
                }
                const writer = sftp.createWriteStream(path);
                writer.cork && writer.cork();
                writer.write(content);
                writer.uncork && writer.uncork();
                writer.end(() => {
                    sftp.end();
                    resolve();
                });
            });
        });
    }

    /**
     * 获取 SFTP 连接
     * @link https://github.com/mscdex/ssh2/blob/master/SFTP.md
     */
    getSftp() {
        let $this = this;
        return new Promise(( resolve, reject ) => {
            $this.client.sftp((err, sftp) => {
                if (err) {
                    reject(err);
                }
                resolve(sftp);
            });
        });
    }
}

export default SSHClient;